package com.xiaosu.red_travel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaosu.red_travel.dao.RouteDao;
import com.xiaosu.red_travel.dao.UserDao;
import com.xiaosu.red_travel.mapper.Comment;
import com.xiaosu.red_travel.mapper.Route;
import com.xiaosu.red_travel.service.RouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

@Service
public class RouteServiceImpl extends ServiceImpl<RouteDao, Route> implements RouteService {

    @Autowired
    private RouteDao routeDao;
    @Autowired
    private UserDao userDao;

    /**
     * 根据id获取景点信息
     * @param id 景点id
     * @return 景点对象
     */
    @Override
    public Route getRouteById(Integer id) {
        Route route = getById(id);
        if(route==null){
            return null;
        }
        List<String> imgList = routeDao.getImgById(id);
        route.setRouteImg(imgList);
        return route;
    }

    /**
     * 根据景点id获取景点评论
     * @param rid 景点id
     * @return 评论集合
     */
    @Override
    public List<Comment> getCommentByRid(Integer rid) {
        return routeDao.getCommentByRid(rid);
    }

    /**
     * 获取所有景点
     * @return
     */
    @Override
    public List<Route> getAllRoute() {
        List<Route> list = list();
        for (Route route : list) {
            List<String> imgById = routeDao.getImgById(route.getId());
            route.setRouteImg(imgById);
        }
        return list;
    }

    /**
     * 获取随机线路
     * @param num 线路条数
     * @return
     */
    @Override
    public List<Route> getRandomRoute(Integer num) {
        // 获取所有有图片的景点id
        Set<String> allId = routeDao.getAllId();
        List<String> ids = new ArrayList<>();
        allId.forEach(ids::add);
        List<String> ranList = new ArrayList<>();
        Random random = new Random();
        if(num>ids.size()){
            num = ids.size();
        }
        for (int i = 0; i < num; i++) {
            int i1 = random.nextInt(ids.size());
            String s = ids.remove(i1);
            ranList.add(s);
        }
        List<Route> list = listByIds(ranList);
        for (Route route : list) {
            route.setRouteImg(routeDao.getImgById(route.getId()));
        }
        return list;
    }

    /**
     * 添加评论数量
     * @param rid
     * @return
     */
    @Override
    public Boolean addCommentCount(Integer rid) {
        return routeDao.addCommentCount(rid)>0;
    }

    /**
     * 添加评论数量
     * @param rid
     * @return
     */
    @Override
    public Boolean addfabulousCount(Integer rid) {
        return routeDao.addfabulousCount(rid)>0;
    }
}
